package com.hama.iotrust.common.atmosphere;

import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.Broadcaster;
import org.atmosphere.cpr.BroadcasterFactory;
import org.atmosphere.cpr.MetaBroadcaster;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hama.iotrust.common.atmosphere.SubscribeUtil;
import com.hama.iotrust.common.util.StrUtil;


/**
 * The Class SubscribeUtil.
 * 服务器向客户端广播工具
 *
 * @author Jinjq
 * @since 2013-11-13 17:57:47
 */
public class SubscribeUtil {

    private static final Logger logger      = LoggerFactory.getLogger(SubscribeUtil.class);

    /**
     * 获取或创建指定路径的广播者
     * @param path
     * @return
     */
    public static Broadcaster getBroadcaster(String path){
        return BroadcasterFactory.getDefault().lookup(path, true);
    }

    /**
     * 获取所有客户端
     * @return
     */
    public static Collection<AtmosphereResource> getAllResources(){
        ConcurrentLinkedQueue<AtmosphereResource> queue = new ConcurrentLinkedQueue<AtmosphereResource>();
        Collection<Broadcaster> allBroadcaster = BroadcasterFactory.getDefault().lookupAll();
        for(Broadcaster broadcaster : allBroadcaster){
            queue.addAll(broadcaster.getAtmosphereResources());
        }
        return queue;
    }

    /**
     * 获取指定路径的所有客户端
     * @param path
     * @return
     */
    public static Collection<AtmosphereResource> getResources(String path){
        ConcurrentLinkedQueue<AtmosphereResource> queue = new ConcurrentLinkedQueue<AtmosphereResource>();

        Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(path);
        if (null != broadcaster){
            queue.addAll(broadcaster.getAtmosphereResources());
        }
        return queue;
    }

    /**
     * 向所有客户端广播
     * @param message
     */
    public static void broadcast(Object message) {
        String json = StrUtil.jsonFromObject(message);
        logger.debug("Broadcast : {}", json);
        MetaBroadcaster.getDefault().broadcastTo("/", json);
    }

    /**
     * 向指定路径的所有客户端广播
     * @param path
     * @param message
     */
    public static void broadcast(String path, Object message) {
        String json = StrUtil.jsonFromObject(message);
        logger.debug("Broadcast : {}", json);
        MetaBroadcaster.getDefault().broadcastTo(path, json);
    }

    /**
     * 向指定客户端广播
     * @param atmosphereResource
     * @param message
     */
    public static void broadcast(AtmosphereResource atmosphereResource, Object message) {
        String json = StrUtil.jsonFromObject(message);
        logger.debug("Broadcast : {}", json);
        atmosphereResource.getBroadcaster().broadcast(json, atmosphereResource);
    }
}
